package com.intct.hbase.ddl.table;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gufg
 * @since 2025-11-03 14:24
 */
public class CreateTable {
    public static void main(String[] args) throws IOException {
        // 客户输入
        Map<String, Integer> clientInputMap = new HashMap<>();
        clientInputMap.put("f1", 3);
        clientInputMap.put("f2", 5);
        clientInputMap.put("f3", 3);

        // 建立连接
        Connection conn = ConnectionFactory.createConnection();

        // 获取Admin实例
        Admin admin = conn.getAdmin();

        // TableName对象
        TableName tableName = TableName.valueOf("intct86", "t3_api");

        try {
            // 判断表是否存在，不存时
            if (!admin.tableExists(tableName)) {

                // 创建表描述
                TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName);

//                // 创建列族描述
//                ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder("f1".getBytes());
//                columnFamilyDescriptorBuilder.setMaxVersions(5);
//
//                // 列族
//                tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());


                // 列表
                List<ColumnFamilyDescriptor> columnFamilyDescriptorList = new ArrayList<>();

                // 创建列族描述
                for (Map.Entry<String, Integer> entry : clientInputMap.entrySet()) {
                    String columnFamily = entry.getKey();
                    Integer versions = entry.getValue();
                    ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(columnFamily.getBytes());
                    columnFamilyDescriptorBuilder.setMaxVersions(versions);
                    columnFamilyDescriptorList.add(columnFamilyDescriptorBuilder.build());
                }

                // 多个列族
                tableDescriptorBuilder.setColumnFamilies(columnFamilyDescriptorList);

                // 预分区
                byte[][] splitKeys = new byte[4][];
                splitKeys[0] = "10".getBytes();
                splitKeys[1] = "20".getBytes();
                splitKeys[2] = "30".getBytes();
                splitKeys[3] = "40".getBytes();

                // 创建表
                admin.createTable(tableDescriptorBuilder.build(), splitKeys);
            }
        } catch (IOException e) {
            System.out.println("创建表失败！");
        } finally {
            // 关闭资源
            if (admin != null) {
                admin.close();
            }
            if (conn != null) {
                conn.close();
            }
        }
    }
}
